package com.ciwong.epaper.modules.me.ui;

import android.content.Intent;
import android.graphics.Color;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.view.ViewGroup;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.me.adapter.MyServicesAdapter;
import com.ciwong.epaper.modules.me.bean.ServiceDetail;
import com.ciwong.epaper.modules.me.dao.MeDao;
import com.ciwong.epaper.modules.me.util.MeJumpManager;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.epaper.widget.DividerItemDecoration;
import com.ciwong.mobilelib.bean.UserInfoBase;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.yanzhenjie.recyclerview.swipe.SwipeItemClickListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenu;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuBridge;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItem;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItemClickListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;

import java.io.Serializable;
import java.util.List;

//import android.support.v7.app.AlertDialog;

/**
 * 我的服务列表界面
 *
 * @author bin
 * @version ciwong v.1.0 2016年04月12日
 * @since ciwong v.1.0
 */
public class MyServicesActivity extends BaseActivity
        implements SwipeItemClickListener {

    private EApplication application;
    private SwipeMenuRecyclerView myServicesRV;
    private MyServicesAdapter adapter;
    private View noDataView;
    private List<ServiceDetail> mServiceDetails;


    @Override
    protected int setView() {
        return R.layout.activity_my_services;
    }

    @Override
    protected void findViews() {
        myServicesRV = (SwipeMenuRecyclerView) findViewById(R.id.my_services_rv);
        noDataView = findViewById(R.id.ll_no_data);
    }

    @Override
    protected void initEvent() {
        myServicesRV.setLayoutManager(new LinearLayoutManager(this));
        myServicesRV.setHasFixedSize(true);
        myServicesRV.addItemDecoration(
                new DividerItemDecoration(this, LinearLayoutManager.VERTICAL, 1, R.color.def_line_color));
        myServicesRV.setSwipeItemClickListener(this);
        myServicesRV.setSwipeMenuCreator(swipeMenuCreator);
        myServicesRV.setSwipeMenuItemClickListener(mMenuItemClickListener);
        adapter = new MyServicesAdapter(this, null);
        myServicesRV.setAdapter(adapter);

    }

    @Override
    protected void init() {
        application = (EApplication) getApplication();
        mServiceDetails = application.getServiceDetails();
        setTitleText(R.string.my_service_list);
    }

    @Override
    protected void loadData() {

        if (null != mServiceDetails) {
            adapter.addAll(mServiceDetails);
        }

        noDataView.setVisibility(
                adapter.getItemCount() <= 0 ? View.VISIBLE : View.GONE);
        showMiddleProgressBar(getTitleText());
        UserInfoBase userInfoBase = application.getUserInfoBase();


        if (null != userInfoBase) {
            MeDao.getInstance().getServiceDetails(application,
                    EApplication.BRAND_ID, userInfoBase.getUserId(), 0,
                    new BaseExtCallBack(MyServicesActivity.this, EApplication.getInstance().getUserInfoBase().getUserId()+"") {

                        @Override
                        public void failed(int errorCode, Object data) {
                            super.failed(errorCode, data);
                            hideMiddleProgressBar();
                        }

                        @Override
                        public void failed(Object data) {
                            super.failed(data);
                            hideMiddleProgressBar();
                        }

                        @Override
                        public void success(Object data) {
                            List<ServiceDetail> list=( List<ServiceDetail>)data;

//                            getServiceListFromNet();
                            noDataView.setVisibility(adapter.getItemCount() <= 0
                                    ? View.VISIBLE : View.GONE);

                            SerializableManager.getInstance().serialize(
                                    SerializableManager.SerializeKey.SHARE_KEY_SERVICE_DETAIL_LIST,
                                    (Serializable) list);
                            application.setServiceDetails(list);

                            adapter.clear();
                            adapter.addAll(list);
                            mServiceDetails=list;
                            adapter.notifyDataSetChanged();
                            hideMiddleProgressBar();
                        }

                    });
        }


    }




    private ServiceDetail mServiceDetail;


    /**
     * 本地化处理
     *
     * @param serviceDetail
     */
    public void localSerializable(ServiceDetail serviceDetail) {
        application.setServiceDetail(serviceDetail);

        SerializableManager.getInstance().serialize(
                SerializableManager.SerializeKey.SHARE_KEY_SERVICE_DETAIL,
                serviceDetail);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case MeFragment.REQUEST_CODE_TO_MY_SERVICES:
                    setResult(RESULT_OK);
                    adapter.notifyDataSetChanged();
                    break;
            }
        }
    }

    public void onItemClick(View view, Object obj) {
        mServiceDetail = (ServiceDetail) obj;
        localSerializable(mServiceDetail);
        int ServiceType = mServiceDetail.getServiceType();
        MeJumpManager.jumpBuyService(MyServicesActivity.this, R.string.go_back, ServiceType,-1, 1,"");

    }


    /**
     * RecyclerView的Item的Menu点击监听。
     */
    private SwipeMenuItemClickListener mMenuItemClickListener = new SwipeMenuItemClickListener() {
        @Override
        public void onItemClick(SwipeMenuBridge menuBridge) {
            menuBridge.closeMenu();

            int direction = menuBridge.getDirection(); // 左侧还是右侧菜单。
            int adapterPosition = menuBridge.getAdapterPosition(); // RecyclerView的Item的position。
            int menuPosition = menuBridge.getPosition(); // 菜单在RecyclerView的Item中的Position。

            mServiceDetail = adapter.mServiceDetails.get(adapterPosition);
            final int index = mServiceDetails.indexOf(mServiceDetail);
            String messageText = mServiceDetail.getServiceTypeName();
            mServiceDetail.setDeleted(true);

            if (null != mServiceDetails) {
                mServiceDetails.set(index, mServiceDetail);
                adapter.clear();
                adapter.addAll(mServiceDetails);
                localSerializable(mServiceDetail);
                application.setServiceDetails(mServiceDetails);
                SerializableManager.getInstance().serialize(
                        SerializableManager.SerializeKey.SHARE_KEY_SERVICE_DETAIL_LIST,
                        (Serializable) mServiceDetails);
                //保存未删除的服务列表
                List<ServiceDetail> existList= adapter.getServiceDetails();

                SerializableManager.getInstance().serialize(
                        SerializableManager.SerializeKey.SHARE_KEY_SERVICE_DETAIL_EXIST_LIST,
                        (Serializable) existList);

                noDataView.setVisibility(
                        adapter.getItemCount() <= 0 ? View.VISIBLE : View.GONE);
            }
        }
    };

    private SwipeMenuCreator swipeMenuCreator = new SwipeMenuCreator() {
        @Override
        public void onCreateMenu(SwipeMenu swipeLeftMenu, SwipeMenu swipeRightMenu, int viewType) {
            if(viewType==MyServicesAdapter.VIEWTYPE_DISDELETEABLE){

            }else{
                int width = getResources().getDimensionPixelSize(R.dimen.dp_70);
                // 1. MATCH_PARENT 自适应高度，保持和Item一样高;
                // 2. 指定具体的高，比如80;
                // 3. WRAP_CONTENT，自身高度，不推荐;
                int height = ViewGroup.LayoutParams.MATCH_PARENT;
                // 添加右侧的，如果不添加，则右侧不会出现菜单。
                {
                    SwipeMenuItem deleteItem = new SwipeMenuItem(MyServicesActivity.this)
                            .setBackground(R.drawable.selector_red)
                            .setImage(R.mipmap.btn_icon_trash)
                            //                            .setText("删除")
                            .setTextColor(Color.WHITE)
                            .setWidth(width)
                            .setHeight(height);
                    swipeRightMenu.addMenuItem(deleteItem);// 添加菜单到右侧。
                }
            }

        }
    };

    @Override
    public void onItemClick(View itemView, int position) {
        mServiceDetail =  mServiceDetails.get(position);
        localSerializable(mServiceDetail);
        int ServiceType = mServiceDetail.getServiceType();
        MeJumpManager.jumpBuyService(MyServicesActivity.this, R.string.go_back, ServiceType,-1, 1,"");
    }
}
